<script setup>
import {onMounted, ref} from 'vue'

defineProps({
  msg: String,
})

let audioCtx;
let animationId;
let analyser;
let frequencyArray;

const byteFrequencyRef = ref();

async function getMusic() {
  fetch('https://static.hanxiaoxin.cn/music/%E5%91%A8%E6%9D%B0%E4%BC%A6-%E6%97%B6%E5%85%89%E6%9C%BA.m4a').then(async (response) => {
    const musicBuffer = await response.arrayBuffer();
    console.log('music buffer', musicBuffer);
    await startAudio(musicBuffer);
  })
}

async function startAudio(musicBuffer) {
  audioCtx = new AudioContext({ sampleRate: 48000 });
  analyser = audioCtx.createAnalyser();
  analyser.fftSize = 2048;
  analyser.minDecibels = -100;
  analyser.maxDecibels = -10;
  analyser.smoothingTimeConstant = 0.8

  const bufferLength = analyser.frequencyBinCount;
  frequencyArray = new Uint8Array(bufferLength);

  await audioCtx.audioWorklet.addModule('my-processor.js');
  const myNode = new AudioWorkletNode(audioCtx, 'my-processor');

  analyser.connect(myNode);
  myNode.connect(audioCtx.destination);

  audioCtx.decodeAudioData(musicBuffer, function(buffer) {
    console.log(buffer)
    const bufferSource = audioCtx.createBufferSource();
    bufferSource.buffer = buffer;
    bufferSource.connect(analyser);
    bufferSource.start();
  }, function(e) {
    console.error("Error with decoding audio data: " + e.err);
  });

  animationId = requestAnimationFrame(draw);
}

function stopAudio() {
  audioCtx.close();
  cancelAnimationFrame(animationId);
}

function draw() {
  animationId = requestAnimationFrame(draw);
  analyser.getByteFrequencyData(frequencyArray);
  // console.log(frquencyArray);
  drawByteFrequency(frequencyArray);
}

function drawByteFrequency(frequencyArray) {
  const canvas = byteFrequencyRef.value;
  const ctx = canvas.getContext('2d');

  const maxBarHeight = canvas.height * 1.0;
  // console.log(canvas.width, canvas.height)
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  const start = Math.floor(frequencyArray.length);
  const filteredArray = frequencyArray;

  const barWidth = (canvas.width / filteredArray.length);
  const barGap = 1;
  let x = 0;

  // console.log(filteredArray)

  for (let i = 0; i < filteredArray.length; i++) {
    const barHeight = Math.min((filteredArray[i] / 255) * maxBarHeight, maxBarHeight);

    ctx.fillStyle = `#6366f1`;
    const y = canvas.height - barHeight;

    ctx.fillRect(x, y, barWidth, barHeight);
    x += barWidth + barGap;
  }
}
</script>

<template>
  <div class="player-container">
    <div class="frequencyCanvas">
      <canvas id="byteFrequency" ref="byteFrequencyRef" class="frequencyCanvas"></canvas>
    </div>
    <div class="footer">
        <div class="desc">
          <div class="music-title">海上日记</div>
          <div class="music-author">毛不易</div>
        </div>


        <div class="duration">
          <div class="active-duration"></div>
        </div>

      <div class="control">
          <button>上一首</button>
          <button @click="getMusic">播放/暂停</button>
          <button>下一首</button>
      </div>

      <div class="actions">
          <div class="playlist">
            音乐库
          </div>
          <div class="play-config">
            <div class="play-mode">
              <button>模式</button>
            </div>
            <div class="play-volume">
              <button>音量</button>
            </div>
          </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.player-container {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: #2d3364;
  flex-direction: column;
}

.frequencyCanvas {
  width: 100%;
  height: calc(100% - 272px);
  display: flex;
  justify-content: center;
  align-items: center;
}

.desc {
  padding: 24px 0;

  .music-title {
    line-height: 28px;
    font-size: 20px;
  }

  .music-author {
    margin-top: 8px;
    line-height: 20px;
    font-size: 14px;
    color: #D1D5DB;
  }
}

.duration {
  width: 100%;
  background-color: #374151;
  height: 4px;

  .active-duration {
    width: 50%;
    background-color: #6366F1;
    height: 100%;
  }
}

.control {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 64px;
  justify-content: space-between;
  padding: 0 12px;
}

.actions {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;

  .playlist {
    background-color: #575d82;
    width: 96px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 18px;
  }

  .play-config {
    display: flex;
    flex-direction: row;
  }
}

.footer {
  padding: 0 24px;
  height: 272px;
  background-color: #444c74;
  display: flex;
  flex-direction: column;
}
</style>